#!/usr/bin/python -O

import sys
import os
import shutil
from utils import *

class SaveSwitcher:
    def __init__(self):
        self.first_run = False
        home = os.getenv("HOME")
        if home == None:
            home = os.getenv('USERPROFILE')
        save_files = ["qsave.vvv", "tsave.vvv", "unlock.vvv"]
        if sys.platform.startswith("linux"):
            self.savedir = home + "/.vvvvvv"
        elif sys.platform.startswith("darwin"):
            self.savedir = home + "/Documents/VVVVVV/Saves"
        elif sys.platform.startswith("win"):
            self.savedir = home + "\\Documents\\VVVVVV\\Saves"
        else:
            raise OSError
        
        self.profiledir = self.savedir + '/../MultiSave'
        
        self.get_save_list()
        
        if not "unlock.vvv" in self.file_list:
            raise IOError

        self.get_backups()
        return

    def get_backups(self):
        if not os.path.isdir(self.profiledir):
            os.mkdir(self.profiledir)
            self.first_run = True
        self.backup_list = os.listdir(self.profiledir)
        return self.backup_list

    def get_save_list(self):
        self.file_list = sep_extensions(os.listdir(self.savedir), 'vvv')
        return self.file_list

    def backup_save(self, name):
        self.get_save_list()
        if os.path.isdir(self.profiledir + '/' + name):
            return False
        os.mkdir(self.profiledir + '/' + name)
        for item in self.file_list:
            input_file = open(self.savedir + '/' + item, 'r')
            output_file = open(self.profiledir + '/' + name + '/'+ item, 'w')

            input_data = input_file.readlines()
            output_file.writelines(input_data)

            input_file.close()
            output_file.close()

        print "Files written to " + self.profiledir + '/' + name
        return True
            

    def restore_save(self, name):
        self.get_save_list()
        
        for item in self.file_list:
            os.remove(self.savedir + '/' + item)
            input_file = open(self.profiledir + '/' + name + '/' + item, 'r')
            output_file = open(self.savedir + '/' + item, 'w')

            input_data = input_file.readlines()
            output_file.writelines(input_data)

            input_file.close()
            output_file.close()

        return True

    def delete_save(self, name):
        self.get_save_list()
        shutil.rmtree(self.profiledir + '/' + name)
